package com.flex.func.grid
{
	import com.adobe.serialization.json.JSON;
	import com.flex.core.constants.GameConstants;
	import com.flex.core.model.base.GameGridSprite;
	import com.flex.core.model.base.GameUIComponent;

	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;

	import mx.containers.Canvas;
	import mx.controls.Alert;


	public class GridUtil
	{
		public static var start:String="lefttop";

		public static var baseStart:String="lefttop";

		public static var lastBaseUserPos:GameGridSprite;

		public function GridUtil()
		{
		}

		/**
		 * create all gird for this map; first draw outside ; second draw inside;
		 */
		public static function createMapGrid(gridCanv:Canvas, imgWidth:Number, imgHeight:Number, scale:Number):Canvas
		{
			createMapGridAll(gridCanv, imgWidth, imgHeight);
			gridCanv.scaleX=scale;
			gridCanv.scaleY=scale;
			return gridCanv;
		}

		/**
		 * create all gird for this edited map; first draw outside ; second draw inside;
		 */
		public static function createChangedMapGrid(imgPath:String, gridCanv:Canvas, scale:Number):Canvas
		{
			var fs:FileStream=new FileStream();
			var file:File=new File(GameConstants.MAP_WRITE_PATH);
			fs.open(file, FileMode.READ);
			var str:String=fs.readUTFBytes(fs.bytesAvailable);
			var mapArray:Array=new Array();
			var map:Object=null;
			if (str != "" && str.replace(" ", "").length > 0)
			{
				mapArray=JSON.decode(str) as Array;
				if (mapArray != null && mapArray.length > 0)
				{
					for (var i:Number=0; i < mapArray.length; i++)
					{
						var imgPathTemp:String=mapArray[i]["mapPath"];
						if (imgPathTemp == imgPath)
						{
							map=mapArray[i];
							break;
						}
					}
				}
			}
			if (map != null)
			{
				var gridArray:Array=((map["gridArray"])["list"])["source"];
				var len:Number=gridArray.length;
				for (var j:Number=0; j < len; j++)
				{
					var obj:Object=gridArray[j];
					var gamegrid:GameGridSprite=new GameGridSprite(obj["gridWidth"], obj["gridHeight"], obj["mapX"], obj["mapY"], obj["gridState"], obj["id"], obj["gridType"], obj["isBaseUserPosition"]);
					gamegrid.x=obj["x"];
					gamegrid.y=obj["y"];
					var type:Number=gamegrid.gridType;
					var ui:GameUIComponent;
					switch (type)
					{
						case GameConstants.BASE_GRID_TYPE_ONEGRID:
							ui=createOneGameGrid(gamegrid);
							break;
						case GameConstants.BASE_GRID_TYPE_QUARTER_LEFTDOWN:
							ui=createLeftDownQuaterGameGrid(gamegrid);
							break;
						case GameConstants.BASE_GRID_TYPE_QUARTER_LEFTUP:
							ui=createLeftUpQuaterGameGrid(gamegrid);
							break;
						case GameConstants.BASE_GRID_TYPE_QUARTER_RIGHTDOWN:
							ui=createRightDownQuaterGameGrid(gamegrid);
							break;
						case GameConstants.BASE_GRID_TYPE_QUARTER_RIGHTUP:
							ui=createRightUpQuaterGameGrid(gamegrid);
							break;
						default:
							break;
					}
					gridCanv.addChild(ui);
				}
			}
			gridCanv.scaleX=scale;
			gridCanv.scaleY=scale;
			return gridCanv;
		}

		/**
		 * draw outside grid ,there are a quarter grid
		 */
		public static function drawOutSide(maxRow:Number, maxCol:Number, gridCanv:Canvas):void
		{
			start="lefttop";
			baseStart="lefttop";
			for (var i:Number=0; i < maxRow; i++)
			{
				for (var j:Number=0; j < maxCol; j++)
				{
					var gameGrid:GameGridSprite=new GameGridSprite();
					gameGrid.gridWidth=GameConstants.BASE_GRID_WIDTH;
					gameGrid.gridHeight=GameConstants.BASE_GRID_HEIGHT;
					// draw outside
					if (i == 0 || i == maxRow - 1)
					{
						gridCanv.addChild(getCurseQuterUI(gameGrid, i, j));
					}
					else
					{
						if (j == 0 || j == maxCol - 1)
						{
							gridCanv.addChild(getCurseQuterUI(gameGrid, i, j));
						}
					}

					if (start.indexOf("top") > -1)
					{
						start=(start == "lefttop") ? "righttop" : "lefttop";
					}
					else
					{
						start=(start == "leftdown") ? "rightdown" : "leftdown";
					}
				}
				start=baseStart;
				start=(start == "lefttop") ? "leftdown" : "lefttop";
				baseStart=start;
			}
		}

		/**
		 * draw inside grid ,there are one grid
		 */
		public static function drawInSide(maxRow:Number, maxCol:Number, gridCanv:Canvas):void
		{
			for (var i:Number=0; i < maxRow; i++)
			{
				for (var j:Number=0; j < maxCol; j++)
				{
					var gameGrid:GameGridSprite=new GameGridSprite();
					gameGrid.gridWidth=GameConstants.BASE_GRID_WIDTH;
					gameGrid.gridHeight=GameConstants.BASE_GRID_HEIGHT;
					//draw inside
					if (i % 2 == 0 && j % 2 == 0 && i != maxRow - 1 && j != maxCol - 1)
					{
						gridCanv.addChild(getCurseOneUI(gameGrid, i, j));
					}
					if (i % 2 == 1 && j % 2 == 1 && i != maxRow - 1 && j != maxCol - 1)
					{
						gridCanv.addChild(getCurseOneUI(gameGrid, i, j));
					}
				}
				start=baseStart;
				start=(start == "lefttop") ? "leftdown" : "lefttop";
				baseStart=start;
			}
		}

		/**
		 * draw outside grids, these grids are not completed, may be a half of one grid , may be a quarter to one grid;
		 * then draw inside grids, these grids are completed, they are all one grid
		 */
		public static function createMapGridAll(gridCanv:Canvas, imgWidth:Number, imgHeight:Number):void
		{
			var maxRow:Number=(imgHeight / GameConstants.BASE_GRID_HEIGHT) * 2;
			var maxCol:Number=(imgWidth / GameConstants.BASE_GRID_WIDTH) * 2;
			if (maxRow < 2 || maxCol < 2)
			{
				Alert.show("图片太小，无法生成，最少为制定格子大小的一倍！");
				return;
			}
			if (maxCol % 2 == 1 || maxRow % 2 == 1)
			{
				Alert.show("图片大小与格子规则有冲突，必须为制定格子大小的整倍数！");
				return;
			}
			drawOutSide(maxRow, maxCol, gridCanv);
			drawInSide(maxRow, maxCol, gridCanv);
		}

		/**
		 * create a quarter grid by row and col
		 */
		public static function getCurseQuterUI(gameGrid:GameGridSprite, row:Number, col:Number):GameUIComponent
		{
			var ui:GameUIComponent;
			if (start.indexOf("top") > -1)
			{
				ui=(start == "lefttop") ? createRightDownQuaterGameGrid(gameGrid) : createLeftDownQuaterGameGrid(gameGrid);
			}
			else
			{
				ui=(start == "leftdown") ? createRightUpQuaterGameGrid(gameGrid) : createLeftUpQuaterGameGrid(gameGrid);
			}
			gameGrid.x=col * gameGrid.gridWidth / 2;
			gameGrid.y=row * gameGrid.gridHeight / 2;
			gameGrid.mapX=row + 1;
			gameGrid.mapY=col + 1;
			return ui;
		}

		/**
		 * create a grid by row and col
		 */
		public static function getCurseOneUI(gameGrid:GameGridSprite, row:Number, col:Number):GameUIComponent
		{
			var ui:GameUIComponent;
			ui=createOneGameGrid(gameGrid);
			gameGrid.x=col * gameGrid.gridWidth / 2;
			gameGrid.y=(row + 1) * gameGrid.gridHeight / 2;
			gameGrid.mapX=row + 1;
			gameGrid.mapY=col + 1;
			gameGrid.id="map_" + gameGrid.mapX + "_" + gameGrid.mapY;
			return ui;
		}

		/**
		 * when click one grid, judge to change grid state
		 */
		public static function resetGrid(e:MouseEvent):void
		{
			// set gridType
			if (GameConstants.BASE_MOUSE_CURTYPE == GameConstants.BASE_MOUSE_CURTYPE_CHANGEGRID)
			{
				var gameGrid:GameGridSprite=e.currentTarget as GameGridSprite;
				if (gameGrid.gridState != GameConstants.BASE_GRID_STATE_CANMOVE)
				{
					gameGrid.gridState=GameConstants.BASE_GRID_STATE_CANMOVE;
					gameGrid.alpha=GameConstants.BASE_GRID_CANMOVE_ALPHA;
				}
				else
				{
					gameGrid.gridState=GameConstants.BASE_GRID_STATE_CANNOTMOVE
					gameGrid.alpha=GameConstants.BASE_GRID_ALPHA;
				}
			}
			// set baseuserposition
			if (GameConstants.BASE_MOUSE_CURTYPE == GameConstants.BASE_MOUSE_CURTYPE_SETUSERBASEPOS)
			{
				var gameGrid2:GameGridSprite=e.currentTarget as GameGridSprite;
				if (gameGrid2.isBaseUserPosition)
				{
					lastBaseUserPos=null;
					gameGrid2.isBaseUserPosition=false;
					Alert.show("已成功取消用户初始出生位置,请重新选择");
				}
				else
				{
					if (lastBaseUserPos != null)
					{
						lastBaseUserPos.isBaseUserPosition=false;
					}
					gameGrid2.isBaseUserPosition=true;
					lastBaseUserPos=gameGrid2;
					Alert.show("已成功设置用户初始出生位置为 " + gameGrid2.mapX + "_" + gameGrid2.mapY);
				}
			}
		}

		/**
		 * create one grid(base create function)
		 *  *
		 * ***
		 *  *
		 */
		public static function createOneGameGrid(gameGrid:GameGridSprite):GameUIComponent
		{
			gameGrid.gridType=GameConstants.BASE_GRID_TYPE_ONEGRID;
			var width:int=gameGrid.gridWidth;
			var height:int=gameGrid.gridHeight;
			var ui:GameUIComponent=new GameUIComponent();
			gameGrid.graphics.beginFill(GameConstants.BASE_GRID_COLOR);
			gameGrid.graphics.lineStyle(1, 0xFFFFFF);
			gameGrid.graphics.moveTo(0, 0);
			gameGrid.graphics.lineTo(width / 2, -height / 2);
			gameGrid.graphics.lineTo(width, 0);
			gameGrid.graphics.lineTo(width / 2, height / 2);
			gameGrid.graphics.lineTo(0, 0);
			gameGrid.graphics.endFill();
			if (gameGrid.gridState == GameConstants.BASE_GRID_STATE_CANNOTMOVE)
			{
				gameGrid.alpha=GameConstants.BASE_GRID_ALPHA;
			}
			else
			{
				gameGrid.alpha=GameConstants.BASE_GRID_CANMOVE_ALPHA;
			}
			ui.addChild(gameGrid);
			gameGrid.addEventListener(MouseEvent.CLICK, resetGrid);
			return ui;
		}

		/**
		 * create a quator grid,position rightUnder
		 * **
		 * *
		 */
		public static function createRightDownQuaterGameGrid(gameGrid:GameGridSprite):GameUIComponent
		{
			gameGrid.gridType=GameConstants.BASE_GRID_TYPE_QUARTER_RIGHTDOWN;
			var width:int=gameGrid.gridWidth;
			var height:int=gameGrid.gridHeight;
			var ui:GameUIComponent=new GameUIComponent();
			gameGrid.graphics.beginFill(GameConstants.BASE_GRID_COLOR);
			gameGrid.graphics.lineStyle(1, GameConstants.BASE_GRID_LINE_COLOR, GameConstants.BASE_GRID_LINE_ALPHA);
			gameGrid.graphics.moveTo(0, 0);
			gameGrid.graphics.lineTo(width / 2, 0);
			gameGrid.graphics.lineTo(0, height / 2);
			gameGrid.graphics.lineTo(0, 0);
			gameGrid.graphics.endFill();
			ui.addChild(gameGrid);
			ui.alpha=GameConstants.BASE_GRID_ALPHA;
			return ui;
		}

		/**
		 * create a quator grid,position RightUp
		 * *
		 * **
		 */
		public static function createRightUpQuaterGameGrid(gameGrid:GameGridSprite):GameUIComponent
		{
			gameGrid.gridType=GameConstants.BASE_GRID_TYPE_QUARTER_RIGHTUP;
			var width:int=gameGrid.gridWidth;
			var height:int=gameGrid.gridHeight;
			var ui:GameUIComponent=new GameUIComponent();
			gameGrid.graphics.beginFill(GameConstants.BASE_GRID_COLOR);
			gameGrid.graphics.lineStyle(1, GameConstants.BASE_GRID_LINE_COLOR, GameConstants.BASE_GRID_LINE_ALPHA);
			gameGrid.graphics.moveTo(0, 0);
			gameGrid.graphics.lineTo(0, height / 2);
			gameGrid.graphics.lineTo(width / 2, height / 2);
			gameGrid.graphics.lineTo(0, 0);
			gameGrid.graphics.endFill();
			ui.addChild(gameGrid);
			ui.alpha=GameConstants.BASE_GRID_ALPHA;
			return ui;
		}

		/**
		 * create a quator grid,position LeftUp
		 *  *
		 * **
		 */
		public static function createLeftUpQuaterGameGrid(gameGrid:GameGridSprite):GameUIComponent
		{
			gameGrid.gridType=GameConstants.BASE_GRID_TYPE_QUARTER_LEFTUP;
			var width:int=gameGrid.gridWidth;
			var height:int=gameGrid.gridHeight;
			var ui:GameUIComponent=new GameUIComponent();
			gameGrid.graphics.beginFill(GameConstants.BASE_GRID_COLOR);
			gameGrid.graphics.lineStyle(1, GameConstants.BASE_GRID_LINE_COLOR, GameConstants.BASE_GRID_LINE_ALPHA);
			gameGrid.graphics.moveTo(0, height / 2);
			gameGrid.graphics.lineTo(width / 2, height / 2);
			gameGrid.graphics.lineTo(width / 2, 0);
			gameGrid.graphics.lineTo(0, height / 2);
			gameGrid.graphics.endFill();
			ui.addChild(gameGrid);
			ui.alpha=GameConstants.BASE_GRID_ALPHA;
			return ui;
		}

		/**
		 * create a quator grid,position LeftDown
		 * **
		 *  *
		 */
		public static function createLeftDownQuaterGameGrid(gameGrid:GameGridSprite):GameUIComponent
		{
			gameGrid.gridType=GameConstants.BASE_GRID_TYPE_QUARTER_LEFTDOWN;
			var width:int=gameGrid.gridWidth;
			var height:int=gameGrid.gridHeight;
			var ui:GameUIComponent=new GameUIComponent();
			gameGrid.graphics.beginFill(GameConstants.BASE_GRID_COLOR);
			gameGrid.graphics.lineStyle(1, GameConstants.BASE_GRID_LINE_COLOR, GameConstants.BASE_GRID_LINE_ALPHA);
			gameGrid.graphics.moveTo(0, 0);
			gameGrid.graphics.lineTo(width / 2, 0);
			gameGrid.graphics.lineTo(width / 2, height / 2);
			gameGrid.graphics.lineTo(0, 0);
			gameGrid.graphics.endFill();
			ui.addChild(gameGrid);
			ui.alpha=GameConstants.BASE_GRID_ALPHA;
			return ui;
		}

		/**
		 * create a half grid,position Left
		 *  *
		 * **
		 *  *
		 */
		public static function createLeftHalfGameGrid(gameGrid:GameGridSprite):GameUIComponent
		{
			var width:int=gameGrid.gridWidth;
			var height:int=gameGrid.gridHeight;
			var ui:GameUIComponent=createOneGameGrid(gameGrid);
			ui.width=width / 2;
			ui.height=height;
			ui.x=-1;
			ui.y=-1;
			gameGrid.x=0;
			gameGrid.y=0;
			return ui;
		}

		/**
		 * create a half grid,position Right
		 *  *
		 *  **
		 *  *
		 */
		public static function createRightHalfGameGrid(gameGrid:GameGridSprite):GameUIComponent
		{
			var width:int=gameGrid.gridWidth;
			var height:int=gameGrid.gridHeight;
			var ui:GameUIComponent=createOneGameGrid(gameGrid);
			ui.width=width / 2;
			ui.height=height;
			ui.x=-1;
			ui.y=-1;
			gameGrid.x=-width / 2;
			gameGrid.y=0;
			return ui;
		}

		/**
		 * create a half grid,position Up
		 *   *
		 *  ***
		 */
		public static function createUpHalfGameGrid(gameGrid:GameGridSprite):GameUIComponent
		{
			var width:int=gameGrid.gridWidth;
			var height:int=gameGrid.gridHeight;
			var ui:GameUIComponent=createOneGameGrid(gameGrid);
			ui.width=width;
			ui.height=height / 2;
			ui.x=-1;
			ui.y=-1;
			gameGrid.x=0;
			gameGrid.y=0;
			return ui;
		}

		/**
		 * create a half grid,position Down
		 *   *
		 *  ***
		 */
		public static function createDownHalfGameGrid(gameGrid:GameGridSprite):GameUIComponent
		{
			var width:int=gameGrid.gridWidth;
			var height:int=gameGrid.gridHeight;
			var ui:GameUIComponent=createOneGameGrid(gameGrid);
			ui.width=width;
			ui.height=height / 2;
			ui.x=-1;
			ui.y=-1;
			gameGrid.x=0;
			gameGrid.y=-height / 2;
			return ui;
		}
	}
}